
import  logging
import time

# logging.basicConfig(filename='flog.log',format=
# '%(asctime)s %(name)s %(levelname)s %(message)s',level=logging.DEBUG)
# logging.debug("debug message")
# logging.info("debug message")
# logging.warning("debug message")
# logging.error("debug message")
# logging.critical("debug message")
# try:
#     res=1/0
# except Exception as e:
#     logging.error(f'fsfsdf {e}')



#记录日志过程：
# # 创建日志对象
# logger = logging.getLogger('mike')




class LogInfo:

    def __init__(self):
        self.logger = logging.getLogger('mike')

    def set_message(self,level,msg):
        try:
            # 设置日志文件的时间
            str_now = time.strftime('%Y-%m-%d', time.localtime())
            # print(str_now+'.log')
            # 创建文件输出
            fh = logging.FileHandler(str_now + '.log')
            # 创建控制台输出
            ch = logging.StreamHandler()
            # 日志进行格式化
            fm = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s')
            # 格式化方式加入文件
            fh.setFormatter(fm)
            # 格式化方式加入控制台
            ch.setFormatter(fm)
            # 文件对象加入logger
            self.logger.addHandler(fh)
            # 控制台对象加入logger
            self.logger.addHandler(ch)
            # 设置logger 日志级别
            self.logger.setLevel(level=logging.DEBUG)
            if level.lower()=='debug':
                # logger对象输入debug 信息
                self.logger.debug(msg)
            elif level.lower()=='info':
                self.logger.info(msg)
            elif level.lower() == 'warning':
                self.logger.warning(msg)
            elif level.lower() == 'error':
                self.logger.error(msg,exc_info=True,stack_info=True)
            elif level.lower() == 'critical':
                self.logger.critical(msg,exc_info=True,stack_info=True)
            # 移除文件对象
            self.logger.removeHandler(fh)
            # 移除控制台对象
            self.logger.removeHandler(ch)
        except Exception as e:
            print(e)
        finally:
            # 关闭文件对象
            fh.close()
            # 关闭控制对象
            ch.close()


log_info = LogInfo()
log_info.set_message('info','打开浏览器')

try:
    1/0
except Exception as e:
    log_info.set_message('critical',e)
    e.with_traceback()